<script setup>
  import { ref, onMounted } from 'vue'
  import messageApi from '@/apis/message'
  // 任务列表数据
  const notifyList = ref([])
  // 下一页页码
  const nextPage = ref(1)
  // 每页包含数据条数
  const pageSize = ref(5)
  // 是否为空列表
  const isEmpty = ref(false)
  // 是否还有更多数据
  const hasMore = ref(true)
  // 是否加载完成
  const isTriggered = ref(false)

  // 生命周期
  onMounted(() => {
    getNotifyList()
  })

  // 下拉刷新
  async function onScrollViewRefresh() {
    isTriggered.value = true
    await getNotifyList()
    isTriggered.value = false
  }
  //上拉加载更多
  const onScrollToLower = () => {
    //如果没有更多数据了
    if (!hasMore.value) return
    // 获取下一页数据
    getNotifyList(nextPage.value)
  }

  const getNotifyList = async (page = 1, pageSize = 10) => {
    const data = await messageApi.list(201, page, pageSize)
    // 渲染数据
    // notifyList.value = data.items || []

    // 如果是第一页，清空原始的数据
    if (page === 1) notifyList.value = []

    //获取notifyList.value原来的值，追加data.items值
    notifyList.value = [...notifyList.value, ...(data.items || [])]
    //更新下一页
    nextPage.value = ++data.page
    // 是否还有更多数据
    hasMore.value = nextPage.value <= data.pages
    // 是否为空列表
    isEmpty.value = notifyList.value.length === 0
  }

  //全部已读
  const readAll = async () => {
    await messageApi.readAll(201)
    //刷新列表
    isTriggered.value = true
  }
</script>
<template>
  <scroll-view
    class="scroll-view"
    refresher-enabled
    scroll-y
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onScrollViewRefresh"
    :refresher-triggered="isTriggered"
  >
    <view class="scroll-view-wrapper">
      <view class="message-action" @click="readAll">
        <text class="iconfont icon-clear"></text>
        全部已读
      </view>
      <uni-card
        :border="false"
        :is-shadow="false"
        v-for="notify in notifyList"
        :key="notify.id"
      >
        <view class="brief">{{ notify.content }}</view>
        <view class="extra">
          <text class="time">{{ notify.created }}</text>
          <navigator
            hover-class="none"
            class="link"
            :url="`/subpkg_task/detail/index?id=${notify.id}`"
            >查看详情</navigator
          >
        </view>
        <template v-slot:title>
          <!-- notify.isRead = 1表示已读，不显示 -->
          <view :class="{ unread: !notify.isRead }" class="title"
            >您有新的运输任务</view
          >
        </template>
      </uni-card>
      <view v-if="isEmpty" class="message-blank">暂无消息</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
